/**
 * 样式对象转换成样式字符串, 如下:
 * { marginTop: 1px, 'padding-bottom': 2px } => marginTop: 1px; padding-bottom: 2px;
 */
export const paserStyleStr = (attrs) => {
  let styleStr = ''
  Object.keys(attrs).forEach(attr => {
    styleStr += `${attr}: ${attrs[attr]};`
  })

  return styleStr
}

/**
 * 获取值的类型
 * @param {any} val
 * @returns {string} - [string, number, array, object, null, undefined]
 */
export const typeof2 = (val) => {
  const str = Object.prototype.toString.call(val)
  return str.substring(8, str.length - 1).toLocaleLowerCase()
}

// 拷贝
export const copy = data => {
  let result

  try {
    result = JSON.parse(JSON.stringify(data))
  } catch (err) {
    console.error(err)

    result = data
  }

  return result
}

/**
 * 值转换为数字
 * @param {any} str - 被转换的值
 * @param {number} decimal - 转换后保留的位数
 */
export const parseNumber = (str = 0, decimal = 2) => {
  const num = +str

  if (isNaN(num)) return 0

  const x = Math.pow(10, decimal)
  return Math.round(num * x) / x
}

// 将 hex 颜色转成 rgb
export const hexToRgba = (hex, opacity) => {
  const RGBA = 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ',' + parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')'
  return {
    red: parseInt('0x' + hex.slice(1, 3)),
    green: parseInt('0x' + hex.slice(3, 5)),
    blue: parseInt('0x' + hex.slice(5, 7)),
    rgba: RGBA
  }
}
